﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace PocketDeathClock
{
    public partial class frmMain : Form
    {
        public DateTime DeathDate { get; set; }

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            MessageBox.Show("Please tell me a little about yourself.", "Alert!", MessageBoxButtons.OK, 
                MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
            Setup();
        }

        private void menuItemSetup_Click(object sender, EventArgs e)
        {
            Setup();
        }

        private void Setup()
        {
            timer.Enabled = false;

            frmSettings settings = new frmSettings();
            settings.ShowDialog();

            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] randomBytes = new byte[4];

            // Generate 4 random bytes.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(randomBytes);

            // Convert 4 bytes into a 32-bit integer value.
            int seed = (randomBytes[0] & 0x7f) << 24 |
                        randomBytes[1] << 16 |
                        randomBytes[2] << 8 |
                        randomBytes[3];

            long lifeExpectancy = settings.IsMale ? 77 : 81;
            lifeExpectancy -= settings.Age;
            int secondsInAYear = (int)(365.242199 * 24 * 60 * 60);
            lifeExpectancy *= secondsInAYear;
            lifeExpectancy += new Random(seed).Next(0, secondsInAYear);

            DeathDate = DateTime.Now.AddSeconds(lifeExpectancy);

            labelDeathDateValue.Text = DeathDate.ToLongDateString();

            timer.Enabled = true;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            labelSecondsLeftValue.Text = (DeathDate - DateTime.Now).TotalSeconds.ToString();
        }

        private void menuItemAbout_Click(object sender, EventArgs e)
        {
            frmAbout aboutForm = new frmAbout();
            aboutForm.ShowDialog();
        }
    }
}